function [ data ] = improveSet(dataset_name, baseline_name)

load_settings;

% dataset_name = 'SANDBOX_RUN1';
% baseline_name = 'iter_model';

baseline_mat_location = [trained_root baseline_name '.mat'];

data = getData(dataset_name);

load(baseline_mat_location);

%% Calculate xMean

disp('Calculating xMean');
data_dims = size(data);
data = data(:);
hogs = [];
for ix = 1:length(data)
    if ~isempty(data(ix).cam_id)
        if isempty(hogs)
            hogs = data(ix).ppl_hogs;
        else
            hogs = cat(1, hogs, data(ix).ppl_hogs);
        end
    end
end
xMean = mean(hogs,1);

%% Actual work

disp('Starting actual optimization part');
% can this be done as a parfor? Would this make it run faster?
data = arrayfun(@(x) improveImage(x, model.w', xMean'), data);
data = reshape(data, data_dims);

end

% xMean: the average HOG of a person

function [ data ] = improveImage(data, W, xMean)

%% only improves positive examples... doesn't touch negatives
if isempty(data.cam_id)
    return;
end
load_settings;
fn = strcat(image_root, sprintf('%08d',data.cam_id), '/', num2str(data.day), '_', num2str(data.hour, '%06d'), '.jpg');
im = imread(fn);

clf;
figure(1);
imagesc(im);
hold on;

figure(1);
for ix = 1:size(data.ppl_rects,1);
    rectangle('Position',data.ppl_rects(ix,:));
end
hold off;
title('Before optimization');


disp(['local optimizations of rectangles, im: ' fn]);
options = optimset('TolX', .2,'MaxFunEvals', 1000);
for rx = 1:size(data.ppl_rects,1);
    rstart = data.ppl_rects(rx,:);
    % next line is a crappy hack to get fminsearch to have good size initla
    % step size...
    rnew = fminsearch('computeSVMrect',rstart, options, im, W, xMean,rstart);
    data.ppl_rects(rx,:) = rnew;
end

figure(1);
for ix = 1:size(data.ppl_rects,1);
    rectangle('Position',data.ppl_rects(ix,:));
end
hold off;
title('After optimization');

end
